﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using FlowBasis.Json;
using FlowBasis.Configuration;

namespace FlowBasis.Web.Configuration
{
    public class AppSettingsService : IAppSettingsService
    {
        private Func<IJObjectRootMapper> rootMapperFactory;

        public AppSettingsService(Func<IJObjectRootMapper> rootMapperFactory)
        {
            this.rootMapperFactory = rootMapperFactory;
        }


        public string GetString(string name)
        {
            return ConfigurationManager.AppSettings[name];
        }

        public T GetObject<T>(string name, T defaultValue)
        {
            return (T)GetObject(name, defaultValue, typeof(T));
        }

        public object GetObject(string name, object defaultValue, Type targetType)
        {
            string json = ConfigurationManager.AppSettings[name];
            if (json == null)
            {
                return defaultValue;
            }

            object jObject = JObject.Parse(json);

            IJObjectRootMapper rootMapper = this.rootMapperFactory();
            object result = rootMapper.FromJObject(jObject, targetType);

            return result;
        }
    }
}
